
import java.sql.*;
import java.util.ResourceBundle;

/**
 * 实现事务:
 * connection.setAutoCommit(false);
 * connection.commit();
 * // 检查安全,按时回滚
 * connection.rollback();
 */
public class Main {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        ResourceBundle resourceBundle = ResourceBundle.getBundle("03jdbc");

        String driver = resourceBundle.getString("driver");
        String url = resourceBundle.getString("url");
        String user = resourceBundle.getString("user");
        String password = resourceBundle.getString("password");

        System.out.println(driver);

        try {
            // 注册驱动
            Class.forName(driver);
            // 获取连接

            connection = DriverManager.getConnection(url,user,password);
            // 将自动提交机制关闭.也就是开启事务
            connection.setAutoCommit(false);

            // 获取数据库操作对象
            String sql = "insert into stu_work(name,chinsese,math,english) values('jack',99,99,99)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeLargeUpdate(sql);
            // 执行mysql语句.这里的executeQuery 就不要sql作为参数了
           if(resultSet!=null){
               resultSet = preparedStatement.executeQuery();
               int count  = 0;
               if(resultSet.next())
               {
                   String name = resultSet.getString("name");
                   int s = resultSet.getInt("s");
                   System.out.println(name+ s);
                   count++;
               }
               System.out.println(count);
           }
            // 提交事物
            connection.commit();
        } catch (Exception e) {
            // 只要捕捉到了异常就先判断connection,保证数据的安全
            if(connection!=null){
                //
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }
    }
}
